//
//  AppDelegate.m
//  yitaicaijing
//
//  Created by DIANGHONG on 2018/7/9.
//  Copyright © 2018年 DIANGHONG. All rights reserved.
//

#import "AppDelegate.h"

#import <UMPush/UMessage.h>
#import <UMShare/UMShare.h>
#import <UMSocialWechatHandler.h>
#import <SDWebImageDownloader.h>
#import <UMCommon/UMCommon.h>
#import <AFNetworkActivityIndicatorManager.h>


#define UMPush_APPKEY @"5b5fece98f4a9d059700014e"
@interface AppDelegate ()<UNUserNotificationCenterDelegate>
@property (nonatomic, strong) NSDictionary *userInfo;

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    
    //[NSThread sleepForTimeInterval:1];
    //[UMSocialManager]
    //[ums setAppKey:@"5b5fece98f4a9d059700014e"];
    [AFNetworkActivityIndicatorManager sharedManager].enabled = YES;

    [UMConfigure initWithAppkey:UMPush_APPKEY channel:@"App Store"];
   
    /* 打开调试日志 */
    [[UMSocialManager defaultManager] openLog:YES];
    
    

    
    // U-Share 平台设置
    [self configUSharePlatforms];
    [self confitUShareSettings];
    [MobClick setScenarioType:E_UM_NORMAL];
    [MobClick setCrashReportEnabled:YES];

    self.window = [[UIWindow alloc] initWithFrame:kScreenBounds];
    self.window.backgroundColor = UIColor.whiteColor;
    self.window.rootViewController = [[YTMainViewController alloc] init];
    [self.window makeKeyAndVisible];
    
    [self configureUMessageWithLaunchOptions:launchOptions];
    
    // 检查新版本
    [self VersonUpdate];
    
    SDWebImageDownloader *imgDownloader = SDWebImageManager.sharedManager.imageDownloader;
    imgDownloader.headersFilter  = ^NSDictionary *(NSURL *url, NSDictionary *headers) {
        
        NSFileManager *fm = [[NSFileManager alloc] init];
        NSString *imgKey = [SDWebImageManager.sharedManager cacheKeyForURL:url];
        NSString *imgPath = [SDWebImageManager.sharedManager.imageCache defaultCachePathForKey:imgKey];
        NSDictionary *fileAttr = [fm attributesOfItemAtPath:imgPath error:nil];
        
        NSMutableDictionary *mutableHeaders = [headers mutableCopy];
        
        NSDate *lastModifiedDate = nil;
        
        if (fileAttr.count > 0) {
            if (fileAttr.count > 0) {
                lastModifiedDate = (NSDate *)fileAttr[NSFileModificationDate];
            }
            
        }
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
        formatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
        formatter.dateFormat = @"EEE, dd MMM yyyy HH:mm:ss z";
        
        NSString *lastModifiedStr = [formatter stringFromDate:lastModifiedDate];
        lastModifiedStr = lastModifiedStr.length > 0 ? lastModifiedStr : @"";
        [mutableHeaders setValue:lastModifiedStr forKey:@"If-Modified-Since"];
        
        return mutableHeaders;
    };


    return YES;
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    NSLog(@"---applicationDidEnterBackground----");
    //进入后台
    NSLog(@"%@",application);
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    
    NSLog(@"---applicationDidBecomeActive----");
    
    NSLog(@"%@",[[NSUserDefaults standardUserDefaults] objectForKey:YTPushNotificationName]);
    //进入前台
}

// 支持所有iOS系统
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    //6.3的新的API调用，是为了兼容国外平台(例如:新版facebookSDK,VK等)的调用[如果用6.2的api调用会没有回调],对国内平台没有影响
    BOOL result = [[UMSocialManager defaultManager] handleOpenURL:url sourceApplication:sourceApplication annotation:annotation];
    if (!result) {
        // 其他如支付等SDK的回调
    }
    return result;
}


#pragma mark: - 版本更新检查
-(void)VersonUpdate{
    //定义的app的地址
    NSString *urld = [NSString stringWithFormat:@"http://itunes.apple.com/lookup?id=%@",@"1423040714"];
    
    //网络请求app的信息，主要是取得我说需要的Version
    NSURL *url = [NSURL URLWithString:urld];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
                                                           cachePolicy:NSURLRequestReloadIgnoringCacheData
                                                       timeoutInterval:10];
    [request setHTTPMethod:@"POST"];
    
    NSURLSession *session = [NSURLSession sharedSession];
    
    NSURLSessionDataTask *task = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSMutableDictionary *receiveStatusDic=[[NSMutableDictionary alloc]init];
        if (data) {
            
            //data是有关于App所有的信息
            NSDictionary *receiveDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
            if ([[receiveDic valueForKey:@"resultCount"] intValue]>0) {
                
                [receiveStatusDic setValue:@"1" forKey:@"status"];
                [receiveStatusDic setValue:[[[receiveDic valueForKey:@"results"] objectAtIndex:0] valueForKey:@"version"]   forKey:@"version"];
                
                //请求的有数据，进行版本比较
                [self performSelectorOnMainThread:@selector(receiveData:) withObject:receiveStatusDic waitUntilDone:NO];
            }else{
                
                [receiveStatusDic setValue:@"-1" forKey:@"status"];
            }
        }else{
            [receiveStatusDic setValue:@"-1" forKey:@"status"];
        }
    }];
    
    [task resume];
}

#pragma mark: - 版本更新检查的方法
-(void)receiveData:(id)sender
{
    //获取APP自身版本号
    NSString *localVersion = [[[NSBundle mainBundle]infoDictionary]objectForKey:@"CFBundleShortVersionString"];
    
    NSArray *localArray = [localVersion componentsSeparatedByString:@"."];
    NSArray *versionArray = [sender[@"version"] componentsSeparatedByString:@"."];
    
    
    if ((versionArray.count == 3) && (localArray.count == versionArray.count)) {
        
        if ([localArray[0] intValue] <  [versionArray[0] intValue]) {
            [self updateVersion];
        }else if ([localArray[0] intValue]  ==  [versionArray[0] intValue]){
            if ([localArray[1] intValue] <  [versionArray[1] intValue]) {
                [self updateVersion];
            }else if ([localArray[1] intValue] ==  [versionArray[1] intValue]){
                if ([localArray[2] intValue] <  [versionArray[2] intValue]) {
                    [self updateVersion];
                }
            }
        }
    }
}


#pragma mark: - 弹窗提示更新
-(void)updateVersion{
    NSString *msg = [NSString stringWithFormat:@"更新最新版本，优惠信息提前知"];
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"升级提示" message:msg preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *updateAction = [UIAlertAction actionWithTitle:@"现在升级"style:UIAlertActionStyleDestructive handler:^(UIAlertAction*action) {
        
        NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"https://itunes.apple.com/app/id1423040714"]];
        [[UIApplication sharedApplication]openURL:url];
    }];
    
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    
    [alertController addAction:updateAction];
    [alertController addAction:cancelAction];
    
    [self.window.rootViewController presentViewController:alertController animated:YES completion:nil];
    
}



- (void)confitUShareSettings
{
    /*
     * 打开图片水印
     */
    [UMSocialGlobal shareInstance].isUsingWaterMark = false;
    
    
    /*
     * 关闭强制验证https，可允许http图片分享，但需要在info.plist设置安全域名
     <key>NSAppTransportSecurity</key>
     <dict>
     <key>NSAllowsArbitraryLoads</key>
     <true/>
     </dict>
     */
    [UMSocialGlobal shareInstance].isUsingHttpsWhenShareContent = false;
    
}
- (void)applicationWillTerminate:(UIApplication *)application
{
    if (!YTNetworkManager.shareManager.account.auth) {
         [YTNetworkManager.shareManager.requestSerializer setValue:nil forHTTPHeaderField:@"access-token"];
    }
   
}
- (void)configUSharePlatforms
{
    /* 设置微信的appKey和appSecret */
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_WechatSession appKey:@"wx4e1cf8fb121d5aa9" appSecret:@"d80887cd10fb76d5a8daca1aee45e236" redirectURL:@"http://mobile.umeng.com/social"];
    /*
     * 移除相应平台的分享，如微信收藏
     */
    [[UMSocialManager defaultManager] removePlatformProviderWithPlatformTypes:@[@(UMSocialPlatformType_WechatFavorite)]];
    
}

- (void)configureUMessageWithLaunchOptions:(NSDictionary *)launchOptions {
    
    //设置AppKey & LaunchOptions
    // Push组件基本功能配置
    UMessageRegisterEntity * entity = [[UMessageRegisterEntity alloc] init];
    //type是对推送的几个参数的选择，可以选择一个或者多个。默认是三个全部打开，即：声音，弹窗，角标
    entity.types = UMessageAuthorizationOptionBadge|UMessageAuthorizationOptionSound|UMessageAuthorizationOptionAlert;
    [UNUserNotificationCenter currentNotificationCenter].delegate = self;
    [UMessage registerForRemoteNotificationsWithLaunchOptions:launchOptions Entity:entity     completionHandler:^(BOOL granted, NSError * _Nullable error) {
        if (granted) {
            // 用户选择推送
            NSLog(@" 用户选择推送");
            
            // 程序退出处理
            if (launchOptions) {
               
               
                NSDictionary *userInfo = launchOptions[UIApplicationLaunchOptionsRemoteNotificationKey];
//                    NSString *notificationName = [[NSUserDefaults standardUserDefaults] objectForKey:kHomePushNotificationName];
//                    [NSNotificationCenter.defaultCenter postNotificationName:notificationName object:nil userInfo:userInfo];
                NSUserDefaults*pushJudge = [NSUserDefaults standardUserDefaults];
                [pushJudge setObject:@"push"forKey:@"push"];
                [pushJudge synchronize];
////
                BOOL isArticlePush = [userInfo[@"push_isArticle_type"] boolValue];
                NSString *ID = userInfo[@"news_id"];
                UIViewController *detailVC = isArticlePush ? [[YTHomeDetailController alloc] init] : [YTDetailNewController controller];
                isArticlePush ? [(YTHomeDetailController *)detailVC setID:ID] : [(YTDetailNewController *)detailVC setID:ID];
                
                UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:detailVC];
                [self.window.rootViewController presentViewController:nav animated:nil completion:nil];
                
//
////
////                YTMainViewController *mainVC = UIApplication.sharedApplication.keyWindow.rootViewController;
////                UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:detailVC];
////                [mainVC pushViewController:detailVC animated:true];
//                [mainVC.view addSubview:detailVC.view];
            }
        }else{
            NSLog(@" 用户拒绝推送");
        }
    }];

}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    NSLog(@"%@",[[[[deviceToken description] stringByReplacingOccurrencesOfString: @"<" withString: @""]
                  stringByReplacingOccurrencesOfString: @">" withString: @""]
                 stringByReplacingOccurrencesOfString: @" " withString: @""]);
    [UMessage registerDeviceToken:deviceToken];
}

//iOS10以下使用这两个方法接收通知
-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
    [UMessage setAutoAlert:NO];
    if([[[UIDevice currentDevice] systemVersion]intValue] < 10){
        
        // 前台与后台
        if (UIApplication.sharedApplication.applicationState == UIApplicationStateInactive) {
            
            NSString *notificationName = [[NSUserDefaults standardUserDefaults] objectForKey:YTPushNotificationName];
            [NSNotificationCenter.defaultCenter postNotificationName:notificationName object:nil userInfo:userInfo];
            
        }
        [UMessage didReceiveRemoteNotification:userInfo];
    }
    completionHandler(UIBackgroundFetchResultNewData);
}

//iOS10新增：处理前台收到通知的代理方法
-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler{
    
    if ([UIApplication sharedApplication].applicationState == UIApplicationStateActive) {
        return;
    }
     //NSLog(@"%@",[UIApplication sharedApplication].applicationState);
    NSDictionary * userInfo = notification.request.content.userInfo;
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [UMessage setAutoAlert:NO];
        //应用处于前台时的远程推送接受
        //必须加这句代码
        [UMessage didReceiveRemoteNotification:userInfo];
    }else{
        //应用处于前台时的本地推送接受
    }
    completionHandler(UNNotificationPresentationOptionSound|UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionAlert);
}

//iOS10新增：处理后台点击通知的代理方法
-(void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler{
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        
     
        // 前台与后台
        if (UIApplication.sharedApplication.applicationState == UIApplicationStateInactive) {
            
            NSString *notificationName = [[NSUserDefaults standardUserDefaults] objectForKey:YTPushNotificationName];
            [NSNotificationCenter.defaultCenter postNotificationName:notificationName object:nil userInfo:userInfo];
       
            
        }
        
        //应用处于后台时的远程推送接受
        //必须加这句代码
        [UMessage didReceiveRemoteNotification:userInfo];
    }else{
        //应用处于后台时的本地推送接受
//        NSString *notificationName = [[NSUserDefaults standardUserDefaults] objectForKey:kHomePushNotificationName];
//        [NSNotificationCenter.defaultCenter postNotificationName:notificationName object:nil userInfo:userInfo];
    }
    
    completionHandler();
}

@end
